<?php

require_once 'util/class.dbservice.php';
require_once 'util/class.constants.php';

class IdService {
	
	public static function getNextIdRange($name, $range) {
		if($name==null || strlen($name)==0 || $range<=0)
			return Constants::$ID_ERROR;
		
		$db = DBService::getGlobalDb();
		if($db==null)
			return Constants::$ID_ERROR;
		
		try {
			$result=$db->command(array("findAndModify"=>"seq",
					"query"=>array("_id"=>$name),
					"update"=>array('$inc'=>array("value"=>$range)),
					"new"=>true,
					'upsert'=>true));
			if($result==null || $result['ok']!=1)
				return Constants::$ID_ERROR;
			return $result['value']['value'];
		} catch(Exception $e) {
			syslog(LOG_CRIT, "IdService.getNextIdRange, allocate sequence range id failed, name=".$name);
			return Constants::$ID_ERROR;
		}
	}
	
	public static function getNextId($name) {
		if($name==null || strlen($name)==0)
			return Constants::$ID_ERROR;
		
		$db = DBService::getGlobalDb();
		if($db==null)
			return Constants::$ID_ERROR;
		
		try {
			$result=$db->command(array('findAndModify'=>'seq',
					'query'=>array('_id'=>$name),
					'update'=>array('$inc'=>array('value'=>1)),
					'new'=>true,
					'upsert'=>true));
			if(!$result || $result['ok']!=1)
				return Constants::$ID_ERROR;
			return $result['value']['value'];
		} catch(Exception $e) {
			syslog(LOG_CRIT, "IdService.getNextId, allocate sequence id failed, name=".$name);
			return Constants::$ID_ERROR;
		}
	}
	
	public static function getNextIdWithSplitId($name, $splitId) {
		// �����newName��ɹ�����Ҫ��ֿ�ֱ�Ĺ��򱣳�һ��
		$newName=$name.intval($splitId % 100);
		return IdService::getNextId($newName);
	}
}
